/**
 * 
 */
package com.aaron.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import java.io.*;

import com.aaron.client.Document;
import com.aaron.client.DocumentService;

/**
 * @author aaron
 *
 */
public class DocumentServiceImpl extends RemoteServiceServlet implements
		DocumentService {
	static final long serialVersionUID = 456789;
	public Document getDocument(String path, String auth){
		try{
			SessionServer session_server=new SessionServer();
			if(session_server.confirmAndSync(auth)){
				DocumentServer document_server=new DocumentServer();
				String file_contents=document_server.getFileContents(path);
				return new Document(path, file_contents);
			}
		}
		catch(DatabaseException e){
			System.err.println ("deleteProject:DatabaseException "+e.getMessage());
		}
		return new Document(path, "");
	}
	public void setDocument(Document document, String auth){
		try{
			SessionServer session_server=new SessionServer();
			if(session_server.confirmAndSync(auth)){
				DocumentServer document_server=new DocumentServer();
				document_server.setFileContents(document);
				//update the last edit information
				String username=session_server.getUsername(auth);
				String[] parts=document.getPath().split("/");
				for(int i=0; i<parts.length; i++){
					if(parts[i].matches("[0-9a-f]{40}")){
						String project_path=parts[i];
						ProjectServer project_server=new ProjectServer();
						project_server.updateLastEdit(project_path, username);
					}
					
				}
				
				
			}
		}
		catch(DatabaseException e){
			System.err.println ("deleteProject:DatabaseException "+e.getMessage());
		}
	}

	public void mergeDocument(Document document, String auth){
		try{
			SessionServer session_server=new SessionServer();
			if(session_server.confirmAndSync(auth)){
				DocumentServer document_server=new DocumentServer();
				document_server.mergeFileContents(document, auth);
			}
		}
		catch(DatabaseException e){
			System.err.println ("deleteProject:DatabaseException "+e.getMessage());
		}
	}
}
